package user

import (
	"context"
	"fast-boot/app/api/admin/internal/svc"
	"fast-boot/app/api/admin/internal/types"
	"fast-boot/app/model"
	"fast-boot/common/globalkey"
	"github.com/hwUltra/fb-tools/gormx"
	"github.com/jinzhu/copier"

	"github.com/zeromicro/go-zero/core/logx"
)

type PageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 获取用户列表
func NewPageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PageLogic {
	return &PageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PageLogic) Page(req *types.UserPageReq) (resp *types.UserPageRsqp, err error) {
	userModel := model.UserModel{}

	total := int64(0)
	if err := l.svcCtx.GormClient.GormDb.Model(userModel).
		Scopes(userModel.WithKeywords(req.Keywords)).
		Count(&total).Error; err != nil {
		return nil, err
	}
	list := make([]*types.UserInfo, 0)
	if total > 0 {
		items := make([]*model.UserModel, 0)
		l.svcCtx.GormClient.GormDb.Model(userModel).
			Scopes(
				gormx.Paginate(int(req.PageNum), int(req.PageSize)),
				userModel.WithKeywords(req.Keywords)).
			Order("id asc").Find(&items)

		if err := copier.CopyWithOption(&list, items, globalkey.CopierProtoOptions); err != nil {
			return nil, err
		}
	}

	return &types.UserPageRsqp{
		Total: total,
		List:  list,
	}, nil
}
